//
// 嗨~ o(*￣▽￣*)ブ
// Created by Mokou on 2020/7/17.
//

#import "ElecSchedule.h"
#import "Util.h"
#import "GlobalData.h"


@implementation ElecSchedule

- (instancetype)init:(NSDictionary *)_data {
    if (self = super.init) {
        self.id = @"";
        if ([Util notNull:_data k:@"id"])
            self.id = _data[@"id"];

        if ([Util notNull:_data k:@"name"])
            self.name = _data[@"name"];

        NSArray *directionArr = @[@(direction_db_schedule_horizontal), @(direction_db_schedule_vertical)];
        if ([Util notNull:_data k:@"direction"])
            self.direction = [_data[@"direction"] intValue];
        if (![directionArr containsObject:@(self.direction)])
            self.direction = direction_db_schedule_horizontal;

        self.duration = 0L;
        if ([Util notNull:_data k:@"duration"])
            self.duration = [_data[@"duration"] longLongValue];

        self.material_duration = 5000L;
        if ([Util notNull:_data k:@"material_duration"])
            self.material_duration = [_data[@"material_duration"] longLongValue];

        self.size = 0L;
        if ([Util notNull:_data k:@"size"])
            self.size = [_data[@"size"] longLongValue];

        self.createtime = 0L;
        if ([Util notNull:_data k:@"createtime"])
            self.createtime = [_data[@"createtime"] longLongValue];

        self.updatetime = 0L;
        if ([Util notNull:_data k:@"updatetime"])
            self.updatetime = [_data[@"updatetime"] longLongValue];
    }
    return self;
}

- (NSDictionary *)getDict {
    return @{
            @"id" : self.id,
            @"name" : self.name,
            @"direction" : @(self.direction),
            @"duration" : @(self.duration),
            @"material_duration" : @(self.material_duration),
            @"size" : @(self.size),
            @"createtime" : @(self.createtime),
            @"updatetime" : @(self.updatetime),
    };
}

- (void)fillDataByAnotherObj:(ElecSchedule *)elecSchedule {
    if (![Util checkDefined:self.id] && [Util checkDefined:elecSchedule.id]) {
        self.id = elecSchedule.id;
    }
    if ((![Util checkDefined:self.name] || [self.name isEqualToString:@""])&& [Util checkDefined:elecSchedule.name]) {
        self.name = elecSchedule.name;
    }
    if ((![Util checkDefined:@(self.direction)] || self.direction == 0) && [Util checkDefined:@(elecSchedule.direction)]) {
        self.direction = elecSchedule.direction;
    }
    if ((![Util checkDefined:@(self.duration)] || self.duration == 0) && [Util checkDefined:@(elecSchedule.duration)]) {
        self.duration = elecSchedule.duration;
    }
    if ((![Util checkDefined:@(self.material_duration)] || self.material_duration == 0) && [Util checkDefined:@(elecSchedule.material_duration)]) {
        self.material_duration = elecSchedule.material_duration;
    }
    if ((![Util checkDefined:@(self.size)] || self.size == 0) && [Util checkDefined:@(elecSchedule.size)]) {
        self.size = elecSchedule.size;
    }
    if ((![Util checkDefined:@(self.createtime)] || self.createtime == 0) && [Util checkDefined:@(elecSchedule.createtime)]) {
        self.createtime = elecSchedule.createtime;
    }
    if ((![Util checkDefined:@(self.updatetime)] || self.updatetime == 0) &&  [Util checkDefined:@(elecSchedule.updatetime)]) {
        self.updatetime = elecSchedule.updatetime;
    }
}

+ (NSDictionary *)create:(NSDictionary *)_data {
    NSDictionary *scheduleDict = @{@"name": @""};

    if ([Util notNull:_data k:@"data"]) {
        NSDictionary *data = _data[@"data"];
        if ([Util notNull:data k:@"schedule"]) {
            scheduleDict = data[@"schedule"];
        }
    }

    Database* db = [GlobalData shareInstance].db;

    //创建计划
    ElecSchedule *newSchedule = [[ElecSchedule alloc] init:scheduleDict];
    newSchedule.createtime = [Util now];
    newSchedule.updatetime = newSchedule.createtime;
    //返回计划id
    NSString *id = [db schedule_insert:newSchedule];

    return [Util callBackJson:@{@"id": id}];
}

+ (void)delete:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return;
    NSDictionary *data = _data[@"data"];
    if (![Util notNull:data k:@"id"]) return;
    NSString *id = data[@"id"];

    Database* db = [GlobalData shareInstance].db;
    FileSelector* fileSelector = [GlobalData shareInstance].fileSelector;
    NSArray *relationArr_thisSchedule = [db relation_select_by_s_id:id];
    
    NSMutableArray *m_id_arr_thisSchedule = NSMutableArray.new;
    for (NSDictionary *r in relationArr_thisSchedule) {
        [m_id_arr_thisSchedule addObject:r[@"m_id"]];
    }
    
    // 素材依赖相关
    for (NSDictionary *r in relationArr_thisSchedule) {
        BOOL deleteMaterial = YES;
        NSString *m_id = r[@"m_id"];
        NSString *content_for_delete = nil;
        
        NSArray *materialArr = [db material_select:m_id];
        if (materialArr.count) {
            ElecMaterial *material = [[ElecMaterial alloc] init:materialArr[0]];
            if (material.typeHasFile) {
                content_for_delete = material.content;
                NSArray *material_same_md5_arr = [db material_select_md5:material.md5];
                for (NSDictionary *same_md5_data in material_same_md5_arr) {
                    ElecMaterial *material_same_md5 = [[ElecMaterial alloc] init:same_md5_data];
                    if (![m_id_arr_thisSchedule containsObject:material_same_md5.id]) {
                        deleteMaterial = NO;
                        break;
                    }
                }
            }
        }
        
        if (deleteMaterial && content_for_delete) {
            [fileSelector deleteFile:[Util getAbsolutePath:content_for_delete]];
        }
        
        [db material_delete:m_id];
    }

    //删除关系
    [db relation_delete_by_s_id:id];

    //删除计划
    [db schedule_delete:id];
}

+ (void)update:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return;
    NSDictionary *schedule_data = _data[@"data"];
    if (![Util notNull:schedule_data k:@"id"]) return;

    ElecSchedule *schedule = [[ElecSchedule alloc] init:schedule_data];
    schedule.duration = 0L;
    schedule.size = 0L;

    Database* db = [GlobalData shareInstance].db;

    // 更新计划总时长
    NSArray *relationArr = [db relation_select_by_s_id:schedule.id];
    for (NSDictionary *r in relationArr) {
        ElecRelation *relation = [[ElecRelation alloc] init:r];
        NSArray *materialArr = [db material_select:relation.m_id];
        for (NSDictionary *m in materialArr) {
            ElecMaterial *material = [[ElecMaterial alloc] init:m];
            switch (material.type) {
                case type_db_material_text: {
                    break;
                }
                case type_db_material_photo: {
                    schedule.duration += schedule.material_duration;
                    break;
                }
                case type_db_material_video: {
                    schedule.duration += material.duration;
                    break;
                }
                default:{}
            }
            schedule.size += material.size;
        }
    }

    [db schedule_update:schedule];
    [ElecSchedule refreshUpdateTime:schedule.id];
}

+ (NSDictionary *)select:(NSDictionary *)_data {
    NSDictionary *callBackRes = @{};

    if (![Util notNull:_data k:@"data"]) return callBackRes;
    NSDictionary *data = _data[@"data"];
    if (![Util notNull:data k:@"id"]) return callBackRes;
    NSString *id = data[@"id"];

    Database *db = [GlobalData shareInstance].db;

    //查询指定计划
    NSArray *scheduleArr = [db schedule_select:id];
    if (!scheduleArr.count) return callBackRes;
    NSDictionary *schedule_data = scheduleArr[0];

    NSMutableArray *materialArr = NSMutableArray.new;

    //查询包含素材
    NSArray *relationArr = [db relation_select_by_s_id:id];

    for (NSDictionary *relation in relationArr) {
        NSArray *materialArr_select = [db material_select:relation[@"m_id"]];
        if (materialArr_select.count) {
            NSMutableDictionary *material = [materialArr_select[0] mutableCopy];
            material[@"playOrder"] = relation[@"playorder"];

            ElecMaterial *materialObj = [[ElecMaterial alloc] init:material];
            if (materialObj.typeHasFile) {
                material[@"content"] = [Util getAbsolutePath:materialObj.content];
            }
            [materialArr addObject:material];
        }
    }

    callBackRes = [Util callBackJson:@{@"schedule":schedule_data, @"material": materialArr}];

    return callBackRes;
}

+ (NSDictionary *)select_page:(NSDictionary *)_data {
    NSDictionary *callBackRes = @{};

    if (![Util notNull:_data k:@"data"]) return callBackRes;
    NSDictionary *data = _data[@"data"];
    int page = [data[@"page"] intValue];
    int pageSize = [data[@"pageSize"] intValue];

    Database *db = [GlobalData shareInstance].db;
    NSArray *scheduleArr = [db schedule_select_page:page pageSize:pageSize];

    int total = db.countSchedule;
    BOOL isOver = total == scheduleArr.count + page * pageSize;

    callBackRes = [Util callBackJson_select:scheduleArr total:total isOver:isOver];

    return callBackRes;
}

+ (NSDictionary *)check_expired:(NSDictionary *)_data {
    NSDictionary *callBackRes = @{};

    if (![Util notNull:_data k:@"data"]) return callBackRes;
    NSArray *data = _data[@"data"];

    NSMutableArray *resArr = NSMutableArray.new;

    Database *db = [GlobalData shareInstance].db;

    for (NSDictionary *d in data) {
        device_schedule_expired status;
        if (![Util notNull:d k:@"id"]) {
            //非法id 状态设为不存在
            status = device_schedule_validity_notFound;
        } else {
            NSString *param_id = d[@"id"];
            long long int param_updatetime = [d[@"updatetime"] longLongValue];
            NSArray *selectRes = [db schedule_select:param_id];
            if (!selectRes.count) {
                //未找到计划 状态设为不存在
                status = device_schedule_validity_notFound;
            } else {
                ElecSchedule *schedule = [[ElecSchedule alloc] init:selectRes[0]];
                if (![db relation_select_by_s_id:param_id].count) {
                    //计划中无素材
                    status = device_schedule_validity_noMaterial;
                } else {
                    if (!schedule.duration) {
                       //无有效素材
                       status = device_schedule_validity_noEffectMaterial;
                    } else if (param_updatetime >= schedule.updatetime){
                        //有效
                        status = device_schedule_validity_valid;
                    } else {
                        //过期
                        status = device_schedule_validity_expired;
                    }
                }
            }
        }
        [resArr addObject:@{@"id": d[@"id"], @"status":@(status)}];
    }

    callBackRes = [Util callBackJson:resArr];

    return callBackRes;
}

+ (void)clear:(NSDictionary *)_data {
    if (![Util notNull:_data k:@"data"]) return;
    NSDictionary *data = _data[@"data"];
    if (![Util notNull:data k:@"userId"]) return;
    NSString *userId = data[@"userId"];

    //todo userId实际未使用, 目前全部清除
    Database *db = [GlobalData shareInstance].db;
    [db schedule_clear:userId];
}

+ (void)refreshUpdateTime:(NSString *)id {
    Database *db = [GlobalData shareInstance].db;
    ElecSchedule *schedule = ElecSchedule.new;
    schedule.id = id;
    schedule.updatetime = [Util now];
    schedule.name = nil;
    schedule.direction = int_nil;
    schedule.duration = int_nil;
    schedule.material_duration = int_nil;
    schedule.size = int_nil;
    schedule.createtime = int_nil;

    [db schedule_update:schedule];
}

@end
